/**
 * @FileName: DigestService.java
 * @Author
 * @Description:
 * @Date 2016年1月5日 下午1:55:03
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.service;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import cn.hpclub.server.constant.ClientApiConstant;

public class DigestService{
    public static DigestService service = new DigestService();

    public boolean validateDigest(String digest, String timeStamp, String appKey){
        String value = ClientApiConstant.Key.APPKEY + ClientApiConstant.APPKEY_DZG_STRING
                + ClientApiConstant.Key.TIMESTAMP + timeStamp + ClientApiConstant.SECRET_DZG;
        value = stringToMD5(value);
        if(value.equals(digest)){
            return true;
        }
        return false;
    }

    public String stringToMD5(String string){
        byte[] hash;

        try{
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        }
        catch(NoSuchAlgorithmException e){
            e.printStackTrace();
            return null;
        }
        catch(UnsupportedEncodingException e){
            e.printStackTrace();
            return null;
        }

        StringBuffer hex = new StringBuffer(hash.length * 2);
        for(byte b : hash){
            if((b & 0xFF) < 0x10)
                hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }

        return hex.toString();
    }
}
